﻿using System;
using System.Collections.Generic;
using MapDownloader.Core.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MapDownloader.Core.MapProviders
{
    public class GaoDeProvider:BaseMapProvider
    {
       public static readonly GaoDeProvider Instance;
       static GaoDeProvider()
       {
          Instance = new GaoDeProvider();
       }
       protected override string Name => "GaoDe";
       public override BaseImage GetTileImage(TilePoint pos)
       {
          return GetTileUsingHttp(MakeTileImageUrl(pos));
      }

       protected override List<List<LatLngPoint>> GetBoundary(string area)
       {
          var content = GetContentUsingHttp($"http://restapi.amap.com/v3/config/district?key=d2526767057cbe8c9a4c6e1c2aa38e9c&keywords={area}&subdistrict=0&extensions=all");
         if(string.IsNullOrEmpty(content))
            throw new Exception("获取边界时，连接服务器失败");
          var jData = JsonConvert.DeserializeObject<JObject>(content);
          if (jData != null)
          {
             var result=new List<List<LatLngPoint>>();
             if (jData["status"].ToString() == "1")
             {
                var tem = jData["districts"][0]["polyline"].ToString();
                var boundaryArrar = tem.Split("|");
                foreach (var boundary in boundaryArrar)
                {
                   var pointList = new List<LatLngPoint>();
                  var boundaryPoints = boundary.Split(";");
                   foreach (var point in boundaryPoints)
                   {
                      var pointArr = point.Split(",");
                      pointList.Add(new LatLngPoint(double.Parse(pointArr[0]), double.Parse(pointArr[1])));
                   }
                   result.Add(pointList);
               }

                return result;

             }
             else
             {
                throw new Exception($"获取边界时,请求失败，获取的数据为:{content}");
            }
          }
          throw  new Exception("获取边界时,获取的内容为空");
         
       }

       string MakeTileImageUrl(TilePoint pos)
       {
          return string.Format(UrlFormat, pos.X, pos.Y,pos.Z);
       }

      public override List<StorageQueueItem> GetTilePoint(LatLngPoint minPointLatLng, LatLngPoint maxPointLatLng)
      {
         throw new NotImplementedException();
      }

      static readonly string UrlFormat = "http://wprd03.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={0}&y={1}&z={2}&scl=1&ltype=19";
      //static readonly string UrlFormat = "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={0}&y={1}&z={2}";
   }
}
